# from django.shortcuts import render
from django.shortcuts import render, redirect
from django.urls import reverse
from .models import Comment
from django.http import JsonResponse
from django.contrib.contenttypes.models import ContentType
from .forms import CommentForm


from django.contrib.auth.models import User
from datetime import datetime


# Create your views here.

def update_comment(request):
    referer = request.META.get('HTTP_REFERER', reverse('home'))  # reverse反向解析

    comment_form = CommentForm(request.POST, user=request.user)
    # 检查通过
    data = {}
    if comment_form.is_valid():
        comment = Comment()
        comment.user = comment_form.cleaned_data['user']
        comment.text = comment_form.cleaned_data['text']
        comment.content_object = comment_form.cleaned_data['content_object']

        parent = comment_form.cleaned_data['parent']
        # 回复
        if not parent is None:
            comment.root = parent.root if not parent.root is None else parent
            comment.parent = parent
            comment.reply_to = parent.user
        comment.save()


        # ajax返回数据

        data['status'] = 'SUCCESS'
        data['username'] = comment.user.get_nickname_or_username()
        data['comment_time'] = comment.comment_time.timestamp()
        data['text'] = comment.text
        data['content_type'] = ContentType.objects.get_for_model(comment).model
        # 回复
        if not parent is None:
            data['reply_to'] = comment.reply_to.get_nickname_or_username()
        else:
            data['reply_to'] = ''
        data['pk'] = comment.pk
        data['root_pk'] = comment.root.pk if not comment.root is None else ''
    else:
        # return render(request, 'error.html', {'message': comment_form.errors, 'redirect_to': referer})
        data = {}
        data['status'] = 'error'
        data['message'] = list(comment_form.errors.values())[0]
    return JsonResponse(data)
